package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /****
     * 分类添加
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加分类成功");
    }

    /****
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Category>> pageSelect(int page, int pageSize) {
        //1.设置分页
        Page<Category> p = new Page<>(page, pageSize);
        //2.设置按顺序查询条件
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper();
        lqw.orderByAsc(Category::getSort);
        //3.查询
        categoryService.page(p, lqw);
        return R.success(p);
    }

    /***
     * 修改分类
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        boolean flag = categoryService.updateById(category);
        return flag ? R.success("修改成功") : R.error("修改失败");
    }

    /*****
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long id) {
        System.out.println(id);
        boolean flag = categoryService.removeById(id);
        return flag ? R.success("删除成功") : R.error("删除失败");
    }

    /*****
     * 分类列表查询
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        //1.条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();

        //2.设置条件
        lqw.eq(category.getType() != null,Category::getType, category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime);
        //3.查询
        List<Category> list = categoryService.list(lqw);
        //4.返回结果
        return R.success(list);
    }

}
